package com.baomidou.plugin.idea.mybatisx.advance.processor.clazz;

import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.plugin.idea.mybatisx.advance.util.PsiClassUtil;
import com.baomidou.plugin.idea.mybatisx.advance.util.PsiMethodUtil;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiMethod;
import org.jetbrains.annotations.NotNull;

import java.util.*;

/**
 * 给po生成delete方法
 * @author wanglei
 */
public class JoinProcessor extends AbstractMPOnceMethodGenClassProcessor {

    private static final String CLASS_NAME = TableName.class.getName();

    public static final String METHOD_NAME = "join";

    public static final Set<String> JOIN_METHOD = new HashSet<>();

    static{
        JOIN_METHOD.add("innerJoin");
        JOIN_METHOD.add("leftJoin");
        JOIN_METHOD.add("rightJoin");
    }

    public JoinProcessor() {
        super(CLASS_NAME, PsiMethod.class);
    }

    @Override
    String getMethodName() {
        return METHOD_NAME;
    }

    @NotNull
    public Collection<PsiMethod> createToStringMethod(@NotNull PsiClass psiClass, @NotNull PsiElement psiNavTargetElement) {
        final PsiMethod[] classMethods = PsiClassUtil.collectClassMethodsIntern(psiClass);
        List<PsiMethod> methods = new ArrayList<>();
        for (String method : JOIN_METHOD) {
            if (PsiMethodUtil.hasMethodByName(classMethods, method)) {
                continue;
            }
            StringBuilder builder = new StringBuilder();
            try {
                builder.append("public <TG> TG " + method + "(Class<TG> target) {\n" +
                        "       try {\n" +
                        "            return target.newInstance()\n" +
                        "        } catch (InstantiationException e) {\n" +
                        "            e.printStackTrace();\n" +
                        "        } catch (IllegalAccessException e) {\n" +
                        "            e.printStackTrace();\n" +
                        "        }" +
                        "    } ");
                methods.add(PsiMethodUtil.createMethod(psiClass, builder.toString(), psiNavTargetElement));
            } finally {
                //StringBuilderSpinAllocator.dispose(builder);
            }
        }
        return methods;
    }

}
